package com.igeek.boot.controller;

import com.igeek.boot.entity.User;
import com.igeek.boot.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.UUID;

/**
 * @Author fengqq
 * @Description 用户模块--控制层
 * @Date 2024/8/16  14:07
 *
 * 文件上传的定制：
 *      1.MultipartProperties --> spring.servlet.multipart作为前缀来操作
 *        application.properties文件中 修改文件上传的配置信息  spring.servlet.multipart.max-file-size=10MB
 *      2.DispatcherServletAutoConfiguration --> @Bean+@ConditionalOnMissingBean(name = "multipartResolver")
 *        WebMVCConfig配置类中 @Bean提供一个自制的底层组件，beanName="multipartResolver",开启支持post pue方式实现文件上传
 *
 * 使用put方式：
 *      1.在页面中 设置隐藏域的值 <input type="hidden" name="_method" value="put">
 *      2.application.properties文件中 开启隐藏域 spring.mvc.hiddenmethod.filter.enabled=true
 *      3.在controller中的方法上 使用注解@PutMapping
 */
@Controller
@Slf4j
public class UserController {

    //显示login.html页面
    @GetMapping("/login.html")
    public String showLogin(){
        return "login";
    }

    //处理login登录请求 admin 123
    @PostMapping("/login")
    public String handleLogin(
            String username,
            String password,
            Model model,
            HttpSession session){
        log.info("username:{},password:{}",username,password);
        if(!StringUtils.hasLength(username) || !StringUtils.hasLength(password)){
            //登录失败 用户名或密码不能为空
            model.addAttribute("errMsg","用户名或密码不能为空");
            //跳转到登录页面login.html 回显错误消息
            return "login"; //请求转发
        }
        if("admin".equals(username) && "123".equals(password)){
            //在session会话中存储当前登录的信息
            session.setAttribute("username","admin");
            //登录成功 跳转到main.html
            return "redirect:/main.html";//重定向 避免表单重复提交
        }
        //登录失败 用户名或者密码错误
        model.addAttribute("errMsg","用户名或密码错误");
        //跳转到登录页面login.html 回显错误消息
        return "login";
    }

    //显示main.html
    @GetMapping("/main.html")
    public String showMain(@RequestParam(value = "id",required = true) int id) throws CustomException {
        System.out.println("id = " + id);
        if(id==0){
            throw new CustomException("id为零了~");
        }else{
            int i = 1/0;//发生异常
        }
        return "main";
    }

    //用户登出
    @GetMapping("/logout")
    public String handleLogOut(HttpSession session){
        //清空session中所有数据
        session.invalidate();
        //跳转到 login.html
        return "redirect:/login.html";
    }

    //显示basic_table.html
    //配置本地图片服务器：
    //WebMVCConfig：@Configuration+implements WebMvcConfigurer 重写 addResourceHandlers方法
    @GetMapping("/basic_table.html")
    public String showTable(Model model){
        //封装 用户集合数据
        ArrayList<User> users = new ArrayList<>();
        users.add(new User("张三","123456","/pic/cat.jpg"));
        users.add(new User("李四","888888","/pic/cat2.jpg"));
        users.add(new User("王五","555555",null));
        users.add(new User("丽丽","999999","/pic/cat.jpg"));
        //将集合 放置到model域中
        model.addAttribute("users",users);
        return "basic_table";
    }

    //显示form_layouts.html
    @GetMapping("/form_layouts.html")
    public String showFormLayout(){
        return "form_layouts";
    }

    //用户头像上传
    @PutMapping("/upload")
    public String upload(
            User user,
            @RequestPart("picture") MultipartFile picture,
            @RequestPart("pictures") MultipartFile[] pictures
            ) throws IOException {
        //单个文件上传
        if(!picture.isEmpty()){
            //得到原始文件名 hello.jpg
            String oldFileName = picture.getOriginalFilename();
            //生成 新的文件名   uuid
            String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));//扩展名
            String newFileName = UUID.randomUUID()+suffix;
            //一键上传
            picture.transferTo(new File("D:\\133java\\1.SpringBoot\\pic\\",newFileName));
            //存储用户的头像路径
            user.setPhoto("/pic/"+newFileName);
            log.info("upload:user:{}",user);
        }
        //批量文件上传
        if(!ObjectUtils.isEmpty(pictures) && pictures.length>0){
            for (MultipartFile file : pictures) {
                if(!file.isEmpty()){
                    //得到原始文件名 hello.jpg
                    String oldFileName = file.getOriginalFilename();
                    //生成 新的文件名   uuid
                    String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));//扩展名
                    String newFileName = UUID.randomUUID()+suffix;
                    //一键上传
                    file.transferTo(new File("D:\\133java\\1.SpringBoot\\pic\\",newFileName));
                    //存储用户的头像路径
                    user.setPhoto("/pic/"+newFileName);
                    log.info("upload:user:{}",user);
                }
            }
        }

        return "redirect:/main.html";

    }
}










